package com.loong.blog.handler;

import com.loong.blog.handler.exp.IdTypeException;
import org.apache.ibatis.binding.BindingException;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.List;


/**
 * @author loong
 * @date 2025/5/10 9:27
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public String handleBindException(BindException bindException, Model model) {
        BindingResult bindingResult = bindException.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        model.addAttribute("errors", fieldErrors);
        return "/blog/error/bind";
    }

    @ExceptionHandler(IdTypeException.class)
    public String handlerIdTypeException(IdTypeException idTypeException, Model model) {
        model.addAttribute("msg", idTypeException.getMessage());
        return "/blog/error/error";
    }

    @ExceptionHandler(Exception.class)
    public String handlerException(Exception exception, Model model) {
        model.addAttribute("msg", "请稍后重试");
        return "/blog/error/error";
    }
}
